﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using QDP.Platform.ObjService;
using QDP.Platform.Silverlight.Controls;
using QDP.Platform.Silverlight.Tools;
namespace QDP.Platform.Silverlight.Manager
{
    /// <summary>提供对平台组件管理的支持。</summary>
    public class WidgetManager
    {
        /// <summary>获取平台所包含的组件清单。</summary>
        public List<Widget> Widgets { get; private set; }
        /// <summary>以配置信息为参数初始化平台组件管理器。</summary>
        /// <param name="Config"></param>
        public WidgetManager(ConfigObject Config)
        {
            Widgets = new List<Widget>();
            // 遍历组件，并将其追加至组件库
            Config.NavigationConfig.Parts.ForEach(part =>
            {
                ContractCreator(part);
            });
            // 遍历工具，并将其追加至组件库
            Config.NavigationConfig.Tools.ForEach(part =>
            {
                ContractCreator(part, WidgetType.Tool);
            });
        }
        private void FullContract(Widget Parent, NavigationBase Navigation, WidgetType ContractType)
        {
            if (Navigation == null) return;
            string curParms = Navigation.ParmsExpression;

            string parParms = Parent == null
                                    ? string.Empty
                                    : Parent.Navigation == null
                                        ? string.Empty
                                        : Parent.Navigation.ParmsExpression;

            string parms = string.Empty;
            if (string.IsNullOrEmpty(curParms))
                parms = parParms;
            else if (string.IsNullOrEmpty(parParms))
                parms = curParms;
            else if (curParms.Equals(parParms))
                parms = curParms;
            else
                parms = ParmsExpressionHelper.ComineParams(curParms, parParms);

            Widget Contract = new Widget()
            {
                Navigation = Navigation,
                Configs = ParmsExpressionHelper.ToDictionary(parms),// 参数表达式转参数清单
                Type = ContractType
            };
            if (Navigation is NavDirectory)
            {
                #region 处理 NavDirectory
                foreach (var child in (Navigation as NavDirectory).SubNotes)
                {
                    FullContract(Contract, child, ContractType);//保留目录结构
                }
                #endregion //#region 处理 NavDirectory
            }
            else if (Navigation is NavUISLXap)
            {
                #region 处理 NavUISLXap
                // 处理自定义磁贴模板
                if (Contract.Configs.ContainsKey(NParams.CustomTile))
                {
                    string key = Contract.Configs[NParams.CustomTile];
                    if (Application.Current.Resources.Contains(key))
                    {
                        object template = Application.Current.Resources[key];
                        if (template is ControlTemplate)
                            Contract.TileTemplate = template as ControlTemplate;
                    }
                }
                Parent.Children.Add(Contract);
                #endregion //#region 处理 NavUISLXap
            }
            Widgets.Add(Contract);
        }
        private void ContractCreator(NavigationBase Navigation, WidgetType ContractType = WidgetType.Part)
        {
            Widget Contract = new Widget()
            {
                Navigation = Navigation,
                Configs = ParmsExpressionHelper.ToDictionary(Navigation.ParmsExpression),
                Type = ContractType
            };
            Widgets.Add(Contract);
            if (Navigation is NavDirectory)
            {
                foreach (var child in (Navigation as NavDirectory).SubNotes)
                {
                    //2012年9月18日 15:55:36 王鑫 参数继承功能已在服务端处理，客户端读取即可。

                    string curParms = child.ParmsExpression;
                    string parParms = Navigation.ParmsExpression;

                    string parms = string.Empty;
                    if (string.IsNullOrEmpty(curParms))
                        parms = parParms;
                    else if (string.IsNullOrEmpty(parParms))
                        parms = curParms;
                    else if (curParms.Equals(parParms))
                        parms = curParms;
                    else
                        parms = ParmsExpressionHelper.ComineParams(curParms, parParms);

                    child.ParmsExpression = parms;
                    FullContract(Contract, child, ContractType);
                }
            }
        }
        public Widget CreatePartContract(NavUISLXap Navigation, UserControl UI)
        {
            var Contract = new Widget()
            {
                Navigation = Navigation
            };
            var Widget = new WidgetControl()
            {
                Child = UI,
                Widget = Contract
            };
            var Part = new PartControl()
            {
                WidgetContent = Widget,
                Config = ParmsExpressionHelper.ToDictionary(Navigation.ParmsExpression),
                Desc = Navigation,
            };
            Contract.PartElement = Part;
            return Contract;
        }
        /// <summary>获取已经存在的Widget对象，若当前对象不存在或未启动，在返回空；</summary>
        /// <param name="WidgetCode">Widget对象的唯一标识</param>
        /// <returns></returns>
        public Widget GetExistedWidget(string WidgetCode)
        {
            var widgets = Widgets.Where(p => p.Navigation.Code == WidgetCode);
            if (widgets.Count() == 0)
            {
                return null;
            }
            else
            {
                return widgets.First();
            }
        }
        /// <summary>根据应用编码获取并打开一个应用窗口。</summary>
        /// <param name="WidgetCode">要打开应用的编码。</param>
        public void ShowWidget(string WidgetCode)
        {
            GetWidget(WidgetCode, (s) =>
            {
                switch (s.State)
                {
                    case LoadActionState.Complated:
                        if (s.Element.IsShowed)
                            s.Element.Active();
                        else
                            s.Element.Show();
                        break;
                    case LoadActionState.Error:
                        this.ShowMessage(s.Error.Message,s.Error.ToString());
                        break;
                }
            });
        }
        /// <summary>根据应用编码异步请求一个应用对象。</summary>
        /// <param name="WidgetCode">要获得应用的编码。</param>
        /// <param name="action">异步执行操作时所经历的过程反馈。</param>
        public void GetWidget(string WidgetCode, Action<LoadActionArgs> action)
        {
            var widgets = Widgets.Where(p => p.Navigation.Code == WidgetCode);
            if (widgets.Count() == 0)
            {
                action(new LoadActionArgs() { Error = new Exception("CODE:" + WidgetCode + "指向的应用不存在") });
            }
            else
            {
                var widget = widgets.First();
                if (widget.Navigation is NavUISLXap)
                {
                    D.LoadPart(widget, action);
                }
                else
                {
                    action(new LoadActionArgs() { Error = new Exception("CODE:" + WidgetCode + "指向内容不是有效的应用") });
                }
            }
        }
    }
}